package org.basis.algorithm.graph;

import org.basis.algorithm.graph.common.Node;

import java.util.HashSet;
import java.util.Stack;

/**
 * 图的深度优先遍历
 *
 * @author Mr_wenpan@163.com 2021/12/23 14:27
 */
public class Dfs {

    public static void main(String[] args) {

    }

    public static void dfs(Node node) {
        Stack<Node> stack = new Stack<>();
        HashSet<Node> set = new HashSet<>();
        stack.push(node);
        set.add(node);
        System.out.print(node.value + "   ");

        while (!stack.isEmpty()) {
            Node pop = stack.pop();
            for (Node next : pop.nexts) {
                // 如果这个节点以前没看过
                if (!set.contains(next)) {
                    // 将原节点压回去，再压这个没看过的节点
                    stack.push(pop);
                    stack.push(next);
                    set.add(node);
                    System.out.print(next.value + "   ");
                    break;
                }
            }
        }
    }

}
